package com.hyxt.DTO.protocols;

import io.netty.buffer.ByteBuf;

import java.util.Map;

/**
 * @author shenp
 * @version v1.0
 * @Description
 * @Date: Create in 14:21 2017/11/24
 * @Modifide By:
 **/
public abstract class CommonCase implements ICase{

    @Override
    public byte[] disassemblyByByteBuf(ByteBuf in){

        final ByteBuf frame;
//      byte[] datas=(byte[])map.get("data");
//		in.readBytes(datas);
//		log.info(BytesUtil.bytesToHexString(datas));
        final int readIndex = in.readerIndex(); // 读取索引
        final int writeIndex = in.writerIndex(); // 写入索引
        if (writeIndex == readIndex){
            return null;
        }

        if (in.getByte(readIndex) == getDataHead()) {// 开头是7e
            if ((readIndex + 1 != writeIndex) // 两个索引
                    && in.getByte(writeIndex - 1) == getDataEnd()) {// 屁股是7e
                int index = findEndOfLine(in); // 找找中间有没有7e7e
                if (index < 0) { // 这就是没有 说明这是个整包
                    frame = in.readBytes(writeIndex - readIndex);
                } else { // 这就是有，说明是粘包，但是只取第一个包
                    frame = in.readBytes(index - readIndex);
                }
                //完整的数据
                byte[] finalMsg = new byte[frame.readableBytes()];
                frame.readBytes(finalMsg);
                return finalMsg;
            } else { // 屁股不是7e，开头是7e
                int index = findEndOfLine(in);
                if (index < 0) { // 这就是说明，这就是个只有开头的半包
                    return null;
                } else {// 这就是说明，这是个有整包和半包合在一起的包，取一个整包出来
                    frame = in.readBytes(index - readIndex);
                    //完整数据
                    byte[] finalMsg = new byte[frame.readableBytes()];
                    frame.readBytes(finalMsg);
                    return finalMsg;
                }
            }
        } else {// 7e不开头，该忽略忽略
            int index = findEndOfLine(in);
            if (index < 0) {
                in.readerIndex(writeIndex);// 忽略
                return null;
            } else {
                in.readerIndex(index);
                return null;
            }
        }
    }
    private int findEndOfLine(final ByteBuf buffer) {
        final int n = buffer.writerIndex();
        for (int i = buffer.readerIndex(); i < n; i++) {
            final byte b = buffer.getByte(i);
            if (b == getDataEnd()) {
                if (buffer.getByte(i + 1) == getDataHead()) {
                    return i + 1;
                }
            }
        }
        return -1; // Not found.
    }
}
